package com.juc.semaphore.semaphore19;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Semaphore;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

public class ListPool {
    /**
     * 同时有若干个线程可以访问池中的数据，但同时只有一个线程可以获取数据 使用完毕在放
     * 回池中
     */
	private int poolMaxSize = 3;
	private int semaphorePermits = 5;
	private List<String> list = new ArrayList<String>();
	private Semaphore concurrencySemphore = new Semaphore(semaphorePermits);
	private ReentrantLock lock = new ReentrantLock();
	private Condition condition = lock.newCondition();
	public ListPool() {
		super();
		for (int i = 0; i < poolMaxSize; i++) {
			list.add(" 高洪岩 " + (i + 1));
		}
	}
	public String get() {
		String getString  = null;
		try {
			concurrencySemphore.acquire();
			lock.lock();
			while(list.size() == 0) {
				condition.await();
			}
			getString = list.remove(0);
			lock.unlock();
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return getString;
	}
	public void put(String stringValue) {
		lock.lock();
		list.add(stringValue);
	    condition.signalAll();
	    lock.unlock();
	    concurrencySemphore.release();
	}
}
